package exercise;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Exercise009 {
    public static void main(String[] args) throws Exception {
        // test1();
        // test2();
        // test3();
        test4();
    }
    /*
     * 使用ThreadPoolExecutor创建一个忽略最新任务的线程池
     * 1.核心线程数为5
     * 2.最大线程数为10
     * 3.任务队列为100
     * 4.拒绝策略为忽略最新任务
     */
    public static void test1() throws InterruptedException{
        ExecutorService executorService = new ThreadPoolExecutor
        (5, 10, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100), new ThreadPoolExecutor.DiscardPolicy());
        for (int i = 0; i < 100; i++) {
            final int taskId = i;
            executorService.execute(()->{
                System.out.println(Thread.currentThread().getName()+"执行了任务"+taskId);
            });
        }
        executorService.shutdown();
        while (!executorService.isTerminated()) {
            Thread.sleep(1000);
        }
        System.out.println("线程池已关闭");
    }
    /*
     * 扫描指定目录，
     * 并找到名称中包含指定字符的所有普通文件（不包含目录），
     * 并且后续询问用户是否要删除该文件
     */
    public static void test2() throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输⼊要扫描的根⽬录（绝对路径 OR 相对路径):");
        String rootDirectoryPath = scanner.next();

        File rootDirectory = new File(rootDirectoryPath);
        if (!rootDirectory.isDirectory()) {
            System.out.println("您输⼊的根⽬录不存在或者不是⽬录，退出");
            return;
        }

        System.out.println("请输⼊要找出的⽂件名中的字符: ");
        String token = scanner.next();

        List<File> files = new ArrayList<>();
        scanDirectory1(rootDirectory, token, files);
        System.out.println("共找到了符合条件的⽂件 " + files.size() + " 个，它们分别是:");
        for (File file : files) {
            System.out.println(file.getCanonicalPath() + "请问您是否要删除该⽂件(y/n)");
            String answer = scanner.next();
            if (answer.equals("y")) {
                file.delete();
                System.out.println("删除成功");
            }
        }
    }
    private static void scanDirectory1(File rootDirectory, String token, List<File> files) {
        File[] fileList = rootDirectory.listFiles();
        if (fileList == null || fileList.length == 0) {
            return;
        }
        for (File file : fileList) {
            if (file.isDirectory()) {
                scanDirectory1(file, token, files);
            } else {
                if (file.getName().contains(token)) {
                    files.add(file.getAbsoluteFile());
                }
            }
        }
    }
    //进行普通文件的复制 
    public static void test3() throws IOException{   
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输⼊要复制的⽂件（绝对路径 OR 相对路径):");
        String sourcePath = scanner.next();

        File sourceFile = new File(sourcePath);
        if(!sourceFile.exists()){
            System.out.println("⽂件不存在，请确认路径是否正确");
            return;
        }
        if(!sourceFile.isFile()){
            System.out.println("您输⼊的不是普通⽂件，请确认路径是否正确");
            return;
        }

        System.out.print("请输⼊要复制的⽬录（绝对路径 OR 相对路径):");
        String targetPath = scanner.next();
        File targetFile = new File(targetPath);
        if(targetFile.exists()){
            if(targetFile.isDirectory()){
                System.out.println("⽬标路径已经存在，并且是⼀个⽬录，请确认路径是否正确");
                return;
            }
            if(targetFile.isFile()){
                System.out.println("目标路径存在普通文件，是否要覆盖(y/n)");
                String answer = scanner.next();
                if(answer.equals("n")){
                    System.out.println("您选择了不覆盖，程序退出");
                    return;
                }
            }
        }
        try(InputStream is = new FileInputStream(sourceFile);
            OutputStream os = new FileOutputStream(targetFile)){
            byte[] buffer = new byte[1024];
            int len;
            while(true){
                len = is.read(buffer);
                if(len == -1){
                    break;
                }
                os.write(buffer, 0, len);   
            }
                os.flush();
        }
    }
    // 扫描指定目录，并找到名称或者内容中包含指定字符的所有普通文件（不包含目录）
    public static void test4() throws IOException{
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输⼊要扫描的根⽬录（绝对路径 OR 相对路径): ");
        String rootDirectoryPath = scanner.next();

        File rootDirectory = new File(rootDirectoryPath);
        if(!rootDirectory.isDirectory()){
            System.out.println("您输⼊的根⽬录不存在或者不是⽬录，退出");
            return;
        }

        System.out.print("请输⼊要找出的⽂件名中的字符: ");
        String token = scanner.next();
        
        List<File> files = new ArrayList<>();
        scanDirectory2(rootDirectory, token, files);
        System.out.println("共找到了符合条件的⽂件 " + files.size() + " 个，它们分别是:");
        for (File file : files) {
            System.out.println(file.getCanonicalPath());
        }
    }
    private static void scanDirectory2(File rootDirectory, String token, List<File> files) throws IOException{
        File[] fileList = rootDirectory.listFiles();
        if (fileList == null || fileList.length == 0) {
            return;
        }
        for (File file : fileList) {
            if (file.isDirectory()) {
                scanDirectory2(file, token, files);
            } else {
                if (isContentContains(file, token)) {
                    files.add(file.getAbsoluteFile());
                }
            }
        }
    }

    private static boolean isContentContains(File file, String token) throws IOException{
        StringBuilder stringBuilder = new StringBuilder();
        try(InputStream inputStream = new FileInputStream(file);
            Scanner scanner = new Scanner(inputStream,"utf-8")){
                while(scanner.hasNextLine()){
                    stringBuilder.append(scanner.nextLine());
                    stringBuilder.append("\r\n");
                }
        }
        return stringBuilder.indexOf(token) != -1;
    }

    // public static void test5(){  
    // 
    // }

}
